package com.woniu.mall.config;

import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MallOrderQueueConfig {

    public static final String ORDER_EXCHANGE = "mall_order_exchange";
    public static final String DLQ_EXCHANGE = "mall_dlq_exchange";
    public static final String DLQ_ORDER_QUEUE = "mall_dlq_order_queue";
    public static final String ORDER_QUEUE = "mall_order_queue";
    public static final Long X_MESSAGE_TTL = 60 * 1000L;
    public static final String ORDER_TIMEOUT = "mall_order_timeout";
    public static final String X_DEAD_LETTER_ROUTING_KEY = "mall_xdl";

    @Bean
    public Exchange orderExchange(){
        return ExchangeBuilder.directExchange(ORDER_EXCHANGE).durable(true).build();
    }

    @Bean
    public Exchange dlqExchange(){
        return ExchangeBuilder.directExchange(DLQ_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue orderQueue(){
        Map<String,Object> params = new HashMap<>();
        //设置消息过期时间
        params.put("x_message_ttl", X_MESSAGE_TTL);
        //配置死信交换机
        params.put("x-dead-letter-exchange", DLQ_EXCHANGE);
        //配置死信队列路由key
        params.put("x-dead-letter-routing-key", X_DEAD_LETTER_ROUTING_KEY);
        return QueueBuilder.durable(ORDER_QUEUE).withArguments(params).build();
    }

    @Bean
    public Queue dlqOrderQueue(){
        return QueueBuilder.durable(DLQ_ORDER_QUEUE).build();
    }

    @Bean
    public Binding orderBinding(@Qualifier("orderQueue") Queue queue,@Qualifier("dlqExchange")  Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_TIMEOUT).noargs();
    }

    @Bean
    public Binding dlqOrderBinding(@Qualifier("dlqOrderQueue") Queue queue,@Qualifier("dlqExchange")  Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_TIMEOUT).noargs();
    }
}
